package com.hks.common.filter;


import com.hks.common.constant.StatusCode;
import com.hks.common.ex.RequestException;
import com.hks.common.utils.JwtUtil;
import com.hks.common.utils.RedisCache;
import com.hks.pojo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * OncePerRequestFilter  在请求进来前，走一次过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1、获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //没有token，放行，让后面的过滤器进行过滤
            filterChain.doFilter(request, response);
            return;
        }
        //2、解析token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            //将异常抛给全局异常进行处理
            resolver.resolveException(request,response,null,new RequestException(StatusCode.REQUEST_EX,"token失效"));
            return;
        }

        //3、获取用户id，在redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        if (Objects.isNull(loginUser)){
            //将异常抛给全局异常进行处理
            resolver.resolveException(request,response,null,new RequestException(StatusCode.REQUEST_EX,"用户未登陆"));
            //不让直接返回，不继续执行
            return;
        }

        //4、封装authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        //5、存入securityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        filterChain.doFilter(request, response);
    }
}
